<template>
  <div>
    <!-- 打印预览对话框 -->
    <Modal
      v-model:open="visible"
      title="打印预览"
      width="800px"
      :footer="null"
      @cancel="handleCancel"
    >
      <div class="max-h-[70vh] overflow-y-auto pb-16">
        <!-- 打印内容区域 -->
        <div id="printContent" class="p-5 bg-white min-h-[calc(100vh-200px)] flex flex-col">
          <div class="w-full mx-auto font-sans text-base leading-7 text-black flex-1 flex flex-col">
            <!-- 标题 -->
            <div class="text-center mb-5">
              <h2 class="text-2xl font-bold m-0">车辆费用支出单</h2>
            </div>
            
            <!-- 基本信息 -->
            <div class="mb-2">
              <div class="flex justify-between mb-4">
                <div class="flex items-center">
                  <span class="font-normal mr-1.5">公司：</span>
                  <span class="min-w-[100px]">{{ printData.companyName }}</span>
                </div>
                <div class="flex items-center ml-auto">
                  <span class="font-normal mr-1.5">日期：</span>
                  <span class="min-w-[100px]">{{ formatDate(printData.createTime) }}</span>
                </div>
              </div>
              <div class="flex justify-between mb-4">
                <div class="flex items-center">
                  <span class="font-normal mr-1.5">车架号：</span>
                  <span class="min-w-[100px]">{{ printData.frameNo }}</span>
                </div>
              </div>
            </div>
            
            <!-- 费用明细表格 -->
            <div class="mb-2">
              <table class="w-full border-collapse border border-black">
                <thead>
                  <tr>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[60px] text-base">序号</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[120px] text-base">费用名称</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-[100px] text-base">金额</th>
                    <th class="border border-black p-3 text-center bg-gray-100 font-bold w-auto text-base">备注</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">1</td>
                    <td class="border border-black p-3 text-center text-base">上牌过户费</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.plateCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">2</td>
                    <td class="border border-black p-3 text-center text-base">检测报告费</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.checkCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">3</td>
                    <td class="border border-black p-3 text-center text-base">交强险</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.insuranceCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">4</td>
                    <td class="border border-black p-3 text-center text-base">车船税</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.vehicleTaxCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">5</td>
                    <td class="border border-black p-3 text-center text-base">清关费</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.clearCustomsCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">6</td>
                    <td class="border border-black p-3 text-center text-base">报关费</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.declarationCustomsCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">7</td>
                    <td class="border border-black p-3 text-center text-base">运费</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.shipCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                  <tr>
                    <td class="border border-black p-3 text-center text-base">8</td>
                    <td class="border border-black p-3 text-center text-base">{{ printData.otherCostName || '其他费用' }}</td>
                    <td class="border border-black p-3 text-center text-base">{{ formatAmount(printData.otherCost) }}</td>
                    <td class="border border-black p-3 text-center text-base"></td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 合计信息 -->
            <div class="mb-5">
              <div class="flex items-center mb-2.5">
                <span class="font-normal mr-2.5">金额合计：</span>
                <span class="border-b border-black pb-0.5 mr-5">{{ formatAmount(printData.totalAmount) }}元</span>
                <span class="font-normal mr-2.5 ml-5">金额大写：</span>
                <span class="border-b border-black pb-0.5 flex-1">{{ convertToChinese(printData.totalAmount) }}</span>
              </div>
            </div>
            
            <!-- 备注 -->
            <div class="mb-7.5">
              <div class="font-normal mb-2.5">备注：</div>
              <div class="border border-black p-3 min-h-[100px] leading-relaxed text-base">
                {{ printData.remark }}
              </div>
            </div>
            
            <!-- 签名区域 - 固定在底部 -->
            <div class="pt-2 pb-4">
              <div class="flex justify-between">
                <div class="flex items-center">
                  <span class="font-normal mr-2.5">申请人：</span>
                  <span class="border-b border-black min-w-[100px] pb-1 text-center">{{ printData.applicantName }}</span>
                </div>
                <div class="flex items-center">
                  <span class="font-normal mr-2.5">审核人：</span>
                  <span class="border-b border-black min-w-[100px] pb-1 text-center">{{ printData.approverName }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 固定在底部的按钮区域 -->
      <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 flex justify-center gap-3 z-10">
        <Button type="primary" @click="handlePrint">打印</Button>
        <Button @click="handleCancel">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Modal, Button, Space } from 'ant-design-vue';
import printJS from 'print-js';
import html2canvas from 'html2canvas';
import dayjs from 'dayjs';
import nzhcn from 'nzh/cn';
import type { CarCostForm } from '#/api/trade/carCost/model';

const visible = ref(false);
const printData = ref<any>({});

// 格式化日期
const formatDate = (date?: string | Date) => {
  if (!date) return dayjs().format('YYYY年MM月DD日');
  return dayjs(date).format('YYYY年MM月DD日');
};

// 格式化金额
const formatAmount = (amount?: number | string) => {
  if (!amount) return '100';
  return Number(amount).toString();
};

// 数字转中文大写 - 使用nzh包
const convertToChinese = (amount?: number | string) => {
  const num = Number(amount);
  // 使用nzh包转换为中文大写
  return nzhcn.encodeB(num) + '圆';
};

// 打开打印预览
const open = (data?: any) => {
  if (data) {
    printData.value = data;
  }
  visible.value = true;
};

// 关闭对话框
const handleCancel = () => {
  visible.value = false;
};

// 执行打印 - 使用html2canvas转换为图像打印
const handlePrint = async () => {
  const htmlContent = document.getElementById('printContent') as HTMLElement;
  try {
    // 高解像度でキャンバスを生成（表示効果と一致させるため）
    const canvas = await html2canvas(htmlContent, {
      scale: 3, // 高解像度で生成
      useCORS: true,
      allowTaint: true,
      backgroundColor: '#ffffff',
      width: htmlContent.offsetWidth,
      height: htmlContent.offsetHeight,
      logging: false
    });
    
    // 高品質のPNG画像として出力
    const imageDataUrl = canvas.toDataURL('image/png', 1.0);
    
    // 画像を直接印刷（表示効果と完全に一致）
    printJS({
      printable: imageDataUrl,
      type: 'image',
      imageStyle: 'width:100%;height:auto;object-fit:contain;display:block;margin:0;padding:0;',
      style: '@page { size: A4; margin: 15mm 10mm; } @media print { html, body { margin: 0; padding: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; } img { max-width: 100% !important; max-height: 100% !important; object-fit: contain !important; display: block !important; margin: 0 auto !important; padding: 0 !important; page-break-after: avoid !important; page-break-before: avoid !important; page-break-inside: avoid !important; } }',
      scanStyles: false
    });
  } catch (error) {
    console.log('打印调用失败：', error);
  }
};

// 暴露方法给父组件
defineExpose({
  open,
});
</script>
